package com.ruoyi.project.system.file.controller;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.FileType;
import com.ruoyi.common.utils.FileUtils;
import com.ruoyi.common.utils.QiniuUtil;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.constant.BusinessType;
import com.ruoyi.framework.config.QiniuConfig;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.system.file.domain.File;
import com.ruoyi.project.system.file.service.IFileService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

/**
 * 文件上传 信息操作处理
 *
 * @author ruoyi
 * @date 2018-07-16
 */
@Controller
@RequestMapping("/system/file")
public class FileController extends BaseController {
  private String prefix = "system/file";

  @Autowired
  private IFileService fileService;
  @Autowired
  private QiniuConfig qiniuConfig;
  private static String fileServerType;

  static {
    fileServerType = RuoYiConfig.getFileServerType();
  }


  @RequiresPermissions("system:file:view")
  @GetMapping()
  public String file() {
    return prefix + "/file";
  }

  @GetMapping("/uploadview")
  public String uploadView() {
    return prefix + "/fileupload";
  }

  /**
   * 查询文件上传列表
   */
  @RequiresPermissions("system:file:list")
  @GetMapping("/list")
  @ResponseBody
  public TableDataInfo list(File file, HttpServletRequest request) {
    startPage();
    String fileType = request.getParameter("type");
    if(!fileType.isEmpty()) {
      file.setFileType(Integer.valueOf(fileType));
    }
    List<File> list = fileService.selectFileList(file);
    return getDataTable(list);
  }


  /**
   * 删除文件
   */
  @RequiresPermissions("system:file:remove")
  @Log(title = "文件上传", action = BusinessType.DELETE)
  @PostMapping("/remove")
  @ResponseBody
  public AjaxResult remove(Long id) {
    QiniuUtil qiniuUtil = new QiniuUtil();
    String fileUrl = fileService.selectFileById(id).getFileUrl();
    String subFileUrl = fileUrl.substring(0, 17);
    if(fileService.deleteFileByIds(String.valueOf(id)) > 0) {
      if("http://pcoasreeo.".equals(subFileUrl)) {

        try {
          qiniuUtil.delete(fileUrl);
        } catch (IOException e) {
          e.printStackTrace();
          return error("数据库记录删除成功，文件删除失败");
        }
      } else {
        String fileName = RuoYiConfig.getProfile() + fileUrl.replace("/profile/", "");

        boolean b = FileUtils.deleteFile(fileName);
        if(!b) {
          return error("数据库记录删除成功，文件删除失败");
        }
      }
    } else {
      return error();
    }
    return success();
  }


  /**
   * 文件下载
   *
   * @return
   */
  @RequestMapping("download")
  @ResponseBody
  @RequiresPermissions("system:file:download")
  public void download(Long id, HttpServletRequest request, HttpServletResponse response) throws IOException {
    String fileUrl = fileService.selectFileById(id).getFileUrl();
    String subFileUrl = fileUrl.substring(0, 8);

    String name = fileService.selectFileById(id).getFileName();
    name = new String(name.getBytes("UTF-8"), "iso-8859-1");
    InputStream fis;
    try {
      if("/profile".equals(subFileUrl)) {
        String filePath = RuoYiConfig.getProfile() + fileService.selectFileById(id).getFileUrl().replace("/profile/", "");
        fis = new FileInputStream(filePath);
      } else {
        fis = download(fileUrl);
      }
      PrintWriter out = response.getWriter();
      response.reset();
      response.setContentType("application/x-download;charset=UTF-8");
      response.setHeader("Content-Disposition", "attachment;fileName=" + name);
      OutputStream outs = response.getOutputStream();
      byte[] bs = new byte[1024 * 1024];
      int len = 0;
      while ((len = fis.read(bs)) > 0) {
        outs.write(bs, 0, len);
      }
      outs.flush();
      if(fis != null) {
        fis.close();
      }
      if(outs != null) {
        outs.close();
      }
      out.print("success");
      out.flush();
    } catch (Exception e) {
      e.printStackTrace();
    }

  }


  /**
   * 删除
   */
  @PostMapping("/batchRemove")
  @ResponseBody
  @RequiresPermissions("system:file:batchRemove")
  public AjaxResult remove() {
    List<File> list = fileService.selectFileList(new File());
    try {
      for (File file : list) {
        this.remove(file.getFileId());
      }
      return success();
    } catch (Exception e) {
      e.printStackTrace();
      return error();
    }
  }

  @ResponseBody
  @RequestMapping(value = "/upload", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
  @RequiresPermissions("system:file:upload")
  public AjaxResult upload(MultipartHttpServletRequest request, HttpServletResponse response) {

    MultipartHttpServletRequest multipartRequest = request;
    List<MultipartFile> fileList = multipartRequest.getFiles("file_data");
    QiniuUtil qiniuUtil = new QiniuUtil();
    File sysFile;
    for (MultipartFile file : fileList) {
      String fileName = file.getOriginalFilename();
      String fileUrl = FileUtils.renameToUUID(fileName);
      if(Constants.FILE_SERVER_TYPE.equals(RuoYiConfig.getFileServerType())) {
        //上传到本地
        try {
          sysFile = new File(FileType.fileType(fileUrl), "/profile/" + fileUrl, fileName);
          FileUtils.uploadFile(file.getBytes(), RuoYiConfig.getProfile(), fileUrl);
        } catch (Exception e) {
          return error();
        }
      } else {
        //上传到七牛云
        try {
          sysFile = new File(FileType.fileType(fileUrl), qiniuConfig.getPath() + "/" + fileUrl, fileName);
          qiniuUtil.upload(file.getBytes(), fileUrl);
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
          return error();
        }
      }
      if(fileService.saveFile(sysFile) > 0) {
        return success();
      }
    }
    return error();
  }

  public InputStream download(String url) {
    try {
      URL imageUrl = new URL(url);
      HttpURLConnection httpURLConnection = (HttpURLConnection) imageUrl.openConnection();
      httpURLConnection.setRequestMethod("POST");
      httpURLConnection.setConnectTimeout(5 * 1000);
      return httpURLConnection.getInputStream();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return null;
  }


}
